﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.PowerShell;

namespace Mystery.SharePoint.PowerShell
{
	[Cmdlet("Add", "SPMServicePrincipalName")]
	public class AddSpnCmdlet : SPCmdlet
	{
		/// <summary>
		/// The SPN
		/// </summary>
		[Parameter(Mandatory = true)]
		public string Spn { get; set; }
		/// <summary>
		/// The account to connect to the SPN
		/// </summary>
		[Parameter(Mandatory = true)]
		public string Account { get; set; }

		protected override void InternalProcessRecord()
		{
			string spn = this.Spn.Replace("://", "/");
            string domain = Environment.UserDomainName;
			string user = null;

			string[] a = this.Account.Split("\\".ToCharArray());

			if (a.Length == 1)
			{
				user = a[0];
			}
			if (a.Length == 2)
			{
				domain = a[0];
				user = a[1];
			}

			string ldap = "LDAP://" + domain;
			using (DirectoryEntry domainEntry = new DirectoryEntry(ldap))
			using (DirectorySearcher searcher = new DirectorySearcher(domain))
			{
				searcher.Filter = "(sAMAccountName=" + user + ")";

				SearchResult result = searcher.FindOne();
				if (result != null)
				{
					using (DirectoryEntry entry = result.GetDirectoryEntry())
					{
						PropertyValueCollection pvc = entry.Properties["servicePrincipalName"];
						if (pvc.Contains(spn) == false)
						{
							base.Host.UI.WriteLine(string.Format("Adding SPN {0} to account {1}", spn, this.Account));
							pvc.Add(spn);
							entry.CommitChanges();
						}
					}
				}
				else
				{
					base.Host.UI.WriteErrorLine(string.Format(null, "Could not find account: {0}", this.Account));
				}
			}
		}
	}
}
